package org.icress.fusion.b2b

import java.util.Date

import org.icress.fusion.shiro.User
import org.icress.fusion.admin.RecordType

import org.icress.fusion.wf.WorkflowDispatcherService
import org.icress.fusion.wf.WorkflowHistory

import org.icress.fusion.ws.OutBound

class SalesOrder {//客户订单
	
	def workflowDispatcherService
    def outBoundService
    def salesOrderService
    
    RecordType recordType//单别
    String serialNumber//单号
    String accountSerialNumber//客户单号
    Date orderDate//单据日期
    Dealer dealer//客户编号
    String project//项目
    Staff salesMan//业务人员
    Date effectiveDate//订单日期,生效日期
    String status
    Industry industry//订单行业
    String address1//送货地址（一）
    String address2//送货地址（二）
    String description//备注
    User owner//所有人
    Date dateCreated//创建日期
    Date lastUpdated//上次修改日期
    User createdBy//创建人
    User lastModifiedBy//上次修改人
        
    static hasMany = [salesOrderDetails : SalesOrderDetail]

    static constraints = {
        recordType(nullable:false, blank:false, validator: { val, obj -> 
            //验证单身行数是否大于零
            return (obj.salesOrderDetails?.size()?:0 > 0) ? true:false
        })
        serialNumber(nullable:true, blank:false, maxSize:16, validator:{val, obj ->
            return obj.salesOrderService.uniqueSerialNumber(val)
        })
        accountSerialNumber(nullable:true, blank:false, maxSize:16)
        orderDate(nullable:false)
        dealer(nullable:false)
        project(nullable:true, blank:true, maxSize:100)
        salesMan(nullable:false)
        effectiveDate(nullable:true)
        status(nullable:false, blank:false, maxSize:20)
        industry(nullable:false)
        address1(maxSize:72, nullable:true, blank:true)
        address2(maxSize:72, nullable:true, blank:true)
        description(maxSize:255, nullable:true, blank:true)
    }
    
    String toString() {
        return "$id"
    }
    
    //拉起工作流
	def afterInsert(){
        WorkflowHistory.withNewSession{
            def departmentId = Dealer.get(this.dealer.id).department.id
            workflowDispatcherService.checkWorkFlow('salesOrder', this.id, this.recordType.id, departmentId)
		}
	}
    //拉起出站消息
    def beforeUpdate(){
        if(this.status == '待审批（商务部）' && this.getPersistentValue('status') == '待审批（办事处）' ){
            OutBound.withNewSession{
                new OutBound(
                    objectName:'salesOrder'
                    , objectId : this.id
                    , method : 'transferSalesOrder'
                    //, asynchronous : true
                    , owner : this.owner
                    , createdBy : outBoundService.getCurrentUser()
                    , lastModifiedBy : outBoundService.getCurrentUser()
                ).save(flush:true)
            }
        }
    }
    
    static mapping = {
        table 'B2B_SALESORDER'
        salesOrderDetails cascade:"all-delete-orphan", sort:"serialNumber", batchSize: 100
    }
}
